package com.yy.service;

import com.yy.utils.DistributeLockFactory;
import com.yy.utils.ZkDistributeLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author: chen
 * @Date: 2022/9/23 21:39
 * @Desc:
 */
@Service
public class ZkStockService {
    @Autowired
    DistributeLockFactory distributeLockFactory;

    @Autowired
    StringRedisTemplate redisTemplate;

    public void deduct() {
        ZkDistributeLock zkLock = distributeLockFactory.getZkLock("lock");

        zkLock.fairLock();

        try {
            String stock = redisTemplate.opsForValue().get("stock");

            if (null != stock && stock.length() > 0) {
                int count = Integer.parseInt(stock);
                if (count > 0) {
                    redisTemplate.opsForValue().set("stock", String.valueOf(--count));
                }
            }
        } finally {
            zkLock.fairUnlock();
        }
    }
}
